//
//  MILAlarmClockSettingViewController.m
//  MicrowaveInteractionLight
//
//  Created by maple on 2016/12/16.
//  Copyright © 2016年 maple. All rights reserved.
//

#import "MILAlarmClockSettingViewController.h"
#import "MILSelectedAlarmTimeViewController.h"
#import "MILAlarmClockSettingTableViewCell.h"
#import "GetAlarmClock.h"
#import "DeleteAlarmClockApi.h"
#import "SaveAlarmClockApi.h"

@interface MILAlarmClockSettingViewController ()<MILAlarmClockSettingDelegate>
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property(nonatomic,strong)NSMutableArray *myDataMutableArray;
@property(nonatomic,strong)NSMutableArray *myWeekMutableArray;
@property(nonatomic,strong)NSMutableArray *alarmNumberArray;
/** 空数据提示 */
@property (nonatomic,strong) UILabel *emptyLabel;
@end

@implementation MILAlarmClockSettingViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark -- UI
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //初始化UI
    [self initMILAlarmClockSettingView];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(deviceStateChange:) name:@"DeviceStateNotification" object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //请求数据
    //    [self getMILAlarmClockList];
    [self updateDeviceState];
}

- (void)updateDeviceState {
    [[WiFiSendDataManager defaultService] getDeviceState:self.myDeviceModel.mac];
//    [[DTCloudManager defaultJNI_iOS_SDK]sendCommandByFunctionCode:@"1002" functionCommand:@"" deviceMacAddress:self.myDeviceModel.mac];
}

- (void)deviceStateChange:(NSNotification *)notify{
    NSString *content = notify.object;
    NSDictionary *dic = notify.userInfo;
    if ([dic[@"backCode"] isEqualToString:@"1802"]){ // 查询
        NSString *string = [NSString string];
        if (content.length == 86) {
            string = [content substringWithRange:NSMakeRange(14, 70)];
            [self initDeviceStateWithString:string];
        }
    } else if ([dic[@"backCode"] isEqualToString:@"1803"]) {
        if (content.length == 14) {
            [self.myTableView reloadData];
            [SVProgressHUD showSuccessWithStatus:@"操作成功"];
        }
    } else if ([dic[@"backCode"] isEqualToString:@"1804"]) {
        if (content.length == 2) {
            [self.myTableView reloadData];
            [SVProgressHUD showSuccessWithStatus:@"删除闹钟成功"];
        }
    }

}

- (void) initDeviceStateWithString:(NSString *)string {
    [self.alarmNumberArray removeAllObjects];
    [self.myDataMutableArray removeAllObjects];
    for (int i = 0; i < 5; i++) {
        NSString *alarmString = [string substringWithRange:NSMakeRange(i*14, 14)];
        NSString *dataString = [alarmString substringWithRange:NSMakeRange(2, 12)];
        NSString *numberString = [alarmString substringWithRange:NSMakeRange(0, 2)];
        [self.alarmNumberArray addObject:numberString];
        if (![dataString isEqualToString:@"000000000000"]) {
            MILAlarmClockModel *model = [[MILAlarmClockModel alloc]init];
            model.alarmID = numberString;
            model.h = [NSString hexadecimalToDecimal:[dataString substringWithRange:NSMakeRange(0, 2)]];
            model.m = [NSString hexadecimalToDecimal:[dataString substringWithRange:NSMakeRange(2, 2)]];
            model.days = [NSString hexadecimalToDecimal:[dataString substringWithRange:NSMakeRange(4, 2)]];
            model.is_open = [NSString hexadecimalToDecimal:[dataString substringWithRange:NSMakeRange(6, 2)]];
            model.twinkle = [NSString hexadecimalToDecimal:[dataString substringWithRange:NSMakeRange(8, 2)]];
            model.ring = [NSString hexadecimalToDecimal:[dataString substringWithRange:NSMakeRange(10, 2)]];
            [self.myDataMutableArray addObject:model];
        }
    }
    
    if (self.myDataMutableArray.count>0){
        self.emptyLabel.hidden = YES;
    } else {
        self.emptyLabel.hidden = NO;
    }
    [self.myTableView reloadData];

}



//初始化UI
- (void)initMILAlarmClockSettingView
{
    [self.myTableView registerNib:[UINib nibWithNibName:@"MILAlarmClockSettingTableViewCell" bundle:nil] forCellReuseIdentifier:@"MILAlarmClockSettingTableViewCell"];
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)refreshBaseControlValue
{
    [self setNavigationBarTitle:@"闹铃设置"];
    [self setRightButtonImage:[UIImage imageNamed:@"add"]];
    self.navigationBar.backgroundColor = [UIColor blackColor];
    [self setLeftButtonImage:[UIImage imageNamed:@"back_icon"]];
    
    [self.emptyLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view);
    }];
    self.emptyLabel.hidden = YES;
}



- (void)onRightButtonClick:(UIButton *)sender
{
    if (self.myDataMutableArray.count == 5)
    {
        [SVProgressHUD showErrorWithStatus:@"最多只能添加五个闹钟"];
    }
    else
    {
        if (self.alarmNumberArray.count != 0)
        {
            //添加闹钟界面
            MILSelectedAlarmTimeViewController *milSelectedAlarmTimeVC = [[MILSelectedAlarmTimeViewController alloc]init];
            NSString *alarmNumberString = @"";
            for (int i = 0 ; i < self.myDataMutableArray.count ; i++)
            {
                MILAlarmClockModel *model = self.myDataMutableArray[i];
                if (![model.alarmID isEqualToString:self.alarmNumberArray[i]])
                {
                    alarmNumberString = self.alarmNumberArray[i];
                    break;
                }

            }
            milSelectedAlarmTimeVC.alarmNumberString = alarmNumberString;
//            milSelectedAlarmTimeVC.alarmNumberString = self.alarmNumberArray[self.myDataMutableArray.count];
            milSelectedAlarmTimeVC.myFlagString = @"0";
            milSelectedAlarmTimeVC.myDeviceModel = self.myDeviceModel;
            [self.navigationController pushViewController:milSelectedAlarmTimeVC animated:YES];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:@"获取闹钟列表失败"];
        }

    }

}

#pragma mark -- 请求数据
- (void)getMILAlarmClockList
{
    GetAlarmClock *api = [[GetAlarmClock alloc]initWithDictionary:@{@"device_id":self.myDeviceModel.device_id}];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary * myDic = [request responseJSONObject];
        NSLog(@"my Dic == %@ ",myDic);
        if ([myDic[@"errcode"] intValue] == 0) {
            [self.myDataMutableArray removeAllObjects];
            NSArray *returnDataArray = myDic[@"data"];
            for (NSDictionary *dic in returnDataArray) {
                MILAlarmClockModel *model = [[MILAlarmClockModel alloc]init];
                model.alarmID = dic[@"id"];
                model.h = dic[@"h"];
                model.m = dic[@"m"];
                model.days = dic[@"days"];
                model.twinkle = dic[@"twinkle"];
                model.ring = dic[@"ring"];
                model.is_open = dic[@"is_open"];
                model.ctime = dic[@"ctime"];
                [self.myDataMutableArray addObject:model];
            }
            if (self.myDataMutableArray.count>0)
            {
                [self.myWeekMutableArray removeAllObjects];
                self.emptyLabel.hidden = YES;
            } else {
                self.emptyLabel.hidden = NO;
            }
            [self.myTableView reloadData];
        }else{
            [SVProgressHUD showErrorWithStatus:myDic[@"errmsg"]];
        }
        
        
    } failure:^(YTKBaseRequest *request) {
        
        [SVProgressHUD showErrorWithStatus:@"请求失败"];
    }];

}

#pragma mark UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.myDataMutableArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MILAlarmClockSettingTableViewCell  *Cell=[tableView  dequeueReusableCellWithIdentifier:@"MILAlarmClockSettingTableViewCell"];
    MILAlarmClockModel *model = self.myDataMutableArray[indexPath.row];
    //time
    Cell.myTimeLabel.text = [NSString stringWithFormat:@"%02d:%02d",[model.h intValue],[model.m intValue]];
    //isopen
    if ([model.is_open isEqualToString:@"1"]) {
        [Cell.mySwitchAlarmClockClickBtn setBackgroundImage:[UIImage imageNamed:@"openLight"] forState:UIControlStateNormal];
        [Cell.mySwitchAlarmClockClickBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 15)];
        [Cell.mySwitchAlarmClockClickBtn setTitle:@"ON" forState:UIControlStateNormal];
    }
    else
    {
        [Cell.mySwitchAlarmClockClickBtn setBackgroundImage:[UIImage imageNamed:@"closeLight"] forState:UIControlStateNormal];
        [Cell.mySwitchAlarmClockClickBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 20, 0, 0)];
        [Cell.mySwitchAlarmClockClickBtn setTitle:@"OFF" forState:UIControlStateNormal];
    }
   //week 先将10转换为2进制
    NSString *birnaryString = [NSString toBinarySystemWithDecimalSystem:model.days];
    NSLog(@"birnaryString = %@",birnaryString);
    //转换成数组(strtoul([myArr[2] UTF8String],0,16)>>0)&01)
    NSMutableArray *myWeekArray = [NSMutableArray array];
    for (int i = 0; i<8; i++)
    {
        [myWeekArray addObject:[NSString stringWithFormat:@"%lu",(([model.days integerValue]>>i)&01)]];
    }
    [myWeekArray removeObjectAtIndex:7];
    if (myWeekArray.count>0)
    {
        [self.myWeekMutableArray addObject:myWeekArray];
    }
    Cell.delegate = self;
    Cell.myReperitionWeekLabel.text = [self dealWithTheWeekStringWithWeekArray:myWeekArray];
    if (indexPath.row == self.myDataMutableArray.count-1)
    {
        Cell.myLineView.hidden = YES;
    }
    if (self.myDeviceModel)
    {
        Cell.myDeviceNameLabel.text = self.myDeviceModel.name;
    }
    return Cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    MILSelectedAlarmTimeViewController *milSelectedAlarmTimeVC = [[MILSelectedAlarmTimeViewController alloc]init];
    milSelectedAlarmTimeVC.myFlagString = @"1";
    milSelectedAlarmTimeVC.alarmNumberString = self.alarmNumberArray[indexPath.row];
    milSelectedAlarmTimeVC.myDataModel = self.myDataMutableArray[indexPath.row];
    milSelectedAlarmTimeVC.mySelectedArray = self.myWeekMutableArray[indexPath.row];
    milSelectedAlarmTimeVC.myDeviceModel = self.myDeviceModel;
    [self.navigationController pushViewController:milSelectedAlarmTimeVC animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return   0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 0.1;
}


//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
//定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
//进入编辑模式，按下出现的编辑按钮后,进行删除操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        MILAlarmClockModel *model = self.myDataMutableArray[indexPath.row];
        if (model)
        {
            [[AlertViewManager shareManager]initWithMessage:@"是否确认删除该闹钟？" cancleButtonTitle:@"取消" OtherButtonsArray:@[@"确认"] clickAtIndex:^(NSInteger buttonIndex, UIAlertView *alertView) {
                if (buttonIndex == 1) {
                    [[WiFiSendDataManager defaultService] settingDeleteAlarm:self.myDeviceModel.mac value:model.alarmID];
//                    [SVProgressHUD showSuccessWithStatus:@"删除闹钟成功"];
                    [self updateDeviceState];
//                    DeleteAlarmClockApi *api = [[DeleteAlarmClockApi alloc]initWithDictionary:@{@"uid":EXRACT_OBJECT(UID),@"token":EXRACT_OBJECT(TOKEN),@"id":model.alarmID}];
//                    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
//                        NSDictionary * myDic = [request responseJSONObject];
//                        if ([myDic[@"errcode"] intValue] == 0) {
//                            
//                            [SVProgressHUD showSuccessWithStatus:@"删除闹钟成功"];
//                            [self getMILAlarmClockList];
//                        }else{
//                            [SVProgressHUD showErrorWithStatus:myDic[@"errmsg"]];
//                        }
//                        
//                        
//                    } failure:^(YTKBaseRequest *request) {
//                        
//                        [SVProgressHUD showErrorWithStatus:@"请求失败"];
//                    }];
                }
            }];


        }
    }
}
//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

#pragma mark -- MILAlarmClockSettingDelegate
- (void)milAlarmClockSettingSwitchAlarmButtonClick:(UIButton *)btn
{
    MILAlarmClockSettingTableViewCell * cell = nil;
    if ([btn isKindOfClass:[UIButton class]])
    {
        cell = (MILAlarmClockSettingTableViewCell *)[[btn superview]superview];
    }
    
    NSIndexPath *indexPath = [self.myTableView indexPathForCell:cell];
    MILAlarmClockModel *model = self.myDataMutableArray[indexPath.row];
    if ([model.is_open isEqualToString:@"1"])
    {
        btn.selected = NO;
    }
    else
    {
        btn.selected = YES;
    }
    model.is_open = [model.is_open isEqualToString:@"1"]?@"0":@"1";
    if (!self.myDeviceModel)
    {
        [SVProgressHUD showErrorWithStatus:@"设备不存在"];
        return;
    }
    //保存定时器
    NSString *codeString = [NSString stringWithFormat:@"%@%@%@%@%@00%@",model.alarmID,[NSString decimalToHexadecimal:[model.h intValue]],[NSString decimalToHexadecimal:[model.m intValue]],[NSString decimalToHexadecimal:[model.days intValue]],[NSString decimalToHexadecimal:[model.is_open intValue]],[NSString decimalToHexadecimal:[model.ring intValue]]];
    NSLog(@"codeString:%@",codeString);
//    010c0060000051
//    020c006000004
    [[WiFiSendDataManager defaultService] settingAddAlarm:self.myDeviceModel.mac value:codeString];
//    SaveAlarmClockApi *api = [[SaveAlarmClockApi alloc]initWithDictionary:@{@"uid":EXRACT_OBJECT(UID),@"token":EXRACT_OBJECT(TOKEN),@"id":model.alarmID,@"device_id":self.myDeviceModel.device_id,@"h":model.h,@"m":model.m,@"days":model.days,@"twinkle":model.twinkle,@"ring":model.ring,@"is_open":model.is_open}];
//    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
//        NSDictionary * myDic = [request responseJSONObject];
//        NSLog(@"my Dic == %@ ",myDic);
//        if ([myDic[@"errcode"] intValue] == 0) {
//            [SVProgressHUD showSuccessWithStatus:@"修改闹钟成功"];
//            [self getMILAlarmClockList];
//        }else{
//            [SVProgressHUD showErrorWithStatus:myDic[@"errmsg"]];
//        }
//        
//        
//    } failure:^(YTKBaseRequest *request) {
//        
//        [SVProgressHUD showErrorWithStatus:@"请求失败"];
//    }];

}

#pragma mark -- 辅助逻辑方法
//一个方法 用来拼接显示的星期字符串
- (NSString *)dealWithTheWeekStringWithWeekArray:(NSArray *)array
{
    NSMutableString *myMutString = [[NSMutableString alloc]init];
    for (int i = 0; i<array.count; i++) {
        NSString *str = array[i];
        if ([str isEqualToString:@"1"]) {
            //通过索引返回周几
            [myMutString appendString:[self dealWithWeekDayStringWithWeekIndex:i]];
        }
    }
    if (myMutString.length>0)
    {
        return [NSString stringWithFormat:@"重复：%@",[myMutString substringFromIndex:1]];
    }
    
    return [myMutString stringByAppendingString:@"单次"];
}

- (NSString *)dealWithWeekDayStringWithWeekIndex:(NSInteger)index
{
    NSString *str;
    switch (index)
    {
        case 0:
        {
            str = @"，一";
        }
            break;
        case 1:
        {
            str = @"，二";
        }
            break;
        case 2:
        {
            str = @"，三";
        }
            break;
        case 3:
        {
            str = @"，四";
        }
            break;
        case 4:
        {
            str = @"，五";
        }
            break;
        case 5:
        {
            str = @"，六";
        }
            break;
        case 6:
        {
            str = @"，日";
        }
            break;
            
        default:
            break;
    }
    
    return str;
}


#pragma mark -- 懒加载
- (NSMutableArray *)myDataMutableArray
{
    
    if (!_myDataMutableArray)
    {
        _myDataMutableArray = [NSMutableArray array];
    }
    
    return _myDataMutableArray;
}

- (NSMutableArray *)myWeekMutableArray
{
    
    if (!_myWeekMutableArray)
    {
        _myWeekMutableArray = [NSMutableArray array];
    }
    
    return _myWeekMutableArray;
}

- (UILabel *)emptyLabel{
    
    if (!_emptyLabel) {
        _emptyLabel = [[UILabel alloc]init];
        _emptyLabel.text = @"暂无闹钟";
        _emptyLabel.font = [UIFont systemFontOfSize:15];
        _emptyLabel.textColor = [UIColor colorWithRed:151/255.0 green:151/255.0 blue:151/255.0 alpha:1];
        [self.view addSubview:_emptyLabel];
    }
    return _emptyLabel;
}

- (NSMutableArray *)alarmNumberArray
{
    if(!_alarmNumberArray)
    {
        _alarmNumberArray = [[NSMutableArray alloc]init];
    }
    return _alarmNumberArray;
}


@end
